package com.cizzy.comment.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LoggingAspect {

    private final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    @Pointcut("execution(* com.cizzy.comment.service.*.*(..))")
    public void servicePointcut() {}

    @Around("servicePointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();// 执行方法
        // 执行方法
        Object result = point.proceed();
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        System.out.println("目标方法"+point.toShortString()+"运行时间："+time+"毫秒");

        return result;
    }



    @Before("servicePointcut()")
    public void logBefore(JoinPoint joinPoint) {
        logger.info("Entering " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + " with 参数 " + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(pointcut = "servicePointcut()", returning = "returnValue")
    public void logAfterReturning(JoinPoint joinPoint, Object returnValue) {
        logger.info("Exiting " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + " with 返回值 " + returnValue);
    }

    @AfterThrowing(pointcut = "servicePointcut()", throwing = "exception")
    public void logAfterThrowing(JoinPoint joinPoint, Exception exception) {
        logger.error("Exception in " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + ": " + exception.getMessage());
    }
}